package khleuven.mondzorg.app;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import khleuven.mondzorg.Logger;
import khleuven.mondzorg.R;
import khleuven.mondzorg.db.DBException;
import khleuven.mondzorg.db.readers.EntryBuilderFactory;
import khleuven.mondzorg.db.readers.EntryBuilderType;
import khleuven.mondzorg.db.writers.OfflineSourceWritingType;
import khleuven.mondzorg.domain.DentalCareApp;
import khleuven.mondzorg.domain.DestinationGroup;
import khleuven.mondzorg.domain.DomainException;
import khleuven.mondzorg.domain.EntryType;
import khleuven.mondzorg.domain.Language;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.Window;

public class SplashScreen extends Activity {
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_splash);        
        
        /**
         * Showing splashscreen while making network calls to download necessary
         * data before launching the app Will use AsyncTask to make http call
         */
        new PrefetchData().execute();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    /**
     * Async Task to load data
     */
    private class PrefetchData extends AsyncTask<Void, Void, Void> {
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute(); 
        }
 
        @Override
        protected Void doInBackground(Void... arg0) {
            // Create a !NEW! instance of the DentalCareApp     
        	DentalCareApp.destroyInstance();        	 	
        	DentalCareApp dca = DentalCareApp.getInstance();
        	
        	// Get the language (from device) and set it in the app!        	
        	dca.setLanguage(Language.getFromString(Locale.getDefault().getDisplayLanguage()));
        	
        	// Get the target (from preferences) and set it in the app!
        	// TODO pref_targetgroup = null
        	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            String chosenValue = prefs.getString("pref_targetgroup", "");  
            Logger.logApp("chosenValue: "+chosenValue);
    		String[] targets = getResources().getStringArray(R.array.Level); 
    		for(int i = 0; i < targets.length; i++){
    			if(chosenValue.equals(targets[i])){
    				dca.setDestination(DestinationGroup.values()[i]);
    			}
    		}
    		
    		// TODO Als nog niet gecheckt in google site via builder uitlezen
    		boolean isConnected = false;
    		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    		NetworkInfo ni = cm.getActiveNetworkInfo();
    		if (ni != null) {
    			isConnected = ni.isConnected();
    			Logger.logApp("Connected: "+isConnected);
    		}
    		
        	try {
        		File filesDir = getFilesDir();
        		List<String> availableFiles = Arrays.asList(filesDir.list());
        		for(EntryType entry: EntryType.values()){
        			String filename = entry.getOfflineFile();
        	 		if(!availableFiles.contains(filename)){
            	 		File f = new File(filesDir, filename);
                		f.createNewFile();
            		}  
        	 		if(isConnected){
        	 			entry.setFileOutputStream(openFileOutput(filename, Context.MODE_PRIVATE));
        	 		}
        	 		entry.setFileInputStream(openFileInput(filename));
        		}
        	} catch (FileNotFoundException e1) {
        		Logger.logApp("Connected: "+isConnected);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
    		
    		// Load all Entrys --> online/offline/hard-coded source!
    		//TODO: check what datasource to use in the settings!
     		try {
    			if(isConnected){
    				EntryBuilderFactory.createEntryBuilderAndLoad(getApplicationContext(), EntryBuilderType.ONLINE);
    				dca.storeOffline(OfflineSourceWritingType.GENERAL);
    			} else {
    				EntryBuilderFactory.createEntryBuilderAndLoad(EntryBuilderType.OFFLINE);
    			}
			} catch (DBException e) {
				Logger.logApp("Something went wrong while loading");
			} catch (DomainException e) {
				Logger.logApp("Something went wrong while loading");
			}
    		
    		return null;
        }
 
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            startActivity(new Intent(SplashScreen.this, MainActivity.class));
            // no need to ever return to this splash screen 
            // --> remove it from the call stack (finish)
            finish();
        } 
    }
    
}
